package com.jing.Recyclerview.listener;

import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jing.Recyclerview.callback.LoadMoreCallback;

public class EndlessScrollListener extends RecyclerView.OnScrollListener {

    private LinearLayoutManager layoutManager;
    private boolean isLoading = false; // 是否正在加载数据
    private boolean isMoreDataAvailable = true; // 是否还有更多数据
    private LoadMoreCallback loadMoreCallback;

    public EndlessScrollListener(LinearLayoutManager layoutManager, LoadMoreCallback loadMoreCallback) {
        this.layoutManager = layoutManager;
        this.loadMoreCallback = loadMoreCallback;
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        if (dy > 0) { // 只处理向下滚动的情况
            int visibleItemCount = layoutManager.getChildCount();
            int totalItemCount = layoutManager.getItemCount();
            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

            if (!isLoading && isMoreDataAvailable) {
                // Check if we need to load more data
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount) {
                    isLoading = true;
                    if (loadMoreCallback != null) {
                        loadMoreCallback.onLoadMore(); // Trigger load more
                    }
                }
            }
        }
    }

    public void setMoreDataAvailable(boolean moreDataAvailable) {
        this.isMoreDataAvailable = moreDataAvailable;
    }

    public void setLoading(boolean loading) {
        this.isLoading = loading;
    }
}
